package se.appening;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class VoterService {
	static Properties storage;
	static File properties = new File("votes.xml");
	static{
		storage = new Properties();
		FileInputStream in;
		try {
			properties.createNewFile();
			in = new FileInputStream(properties);
			storage.loadFromXML(in);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static void Save(){
		FileOutputStream filewriter;
		try {
			filewriter = new FileOutputStream(properties);
			storage.storeToXML(filewriter,"Vote Storage");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static String getVote(String argument) {
		System.out.println("Request for: " + argument);
		String reply = "";
		reply = (String) storage.getProperty(argument,"0");
		return reply +  "\n";
	}

	public static String vote(String argument) {
		
		String reply = "";
		int i;
		if(storage.containsKey(argument)){
			i = Integer.parseInt(storage.getProperty(argument));
		}
		else{
			i = 0;
		}
			if(i != Integer.MAX_VALUE)
				storage.setProperty(argument, String.valueOf(++i));
			reply = "" + i;
		

			System.out.println("Vote for:" + argument + " now got: " + i + " votes");
		Save();
		return reply +  "\n";
	}

}
